package com.hybird.lvgl.voicerecognizeview;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class VoiceRecognizeView extends View {
    private static final String TAG = "VoiceRecognizeView";
    private Paint linePaint;
    private Paint circlePaint;
    private int currentBaseRadio;
    private int radius = 200;
    private int volume = 0;

    public VoiceRecognizeView(Context context) {
        super(context);
        postDelayed(new Runnable() {
            @Override
            public void run() {

            }
        }, 100);
    }

    public VoiceRecognizeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public VoiceRecognizeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        Log.e(TAG, "createAnimation: ");
        createAnimation();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth();
        int height = getHeight();
        int centerX = width / 2;
        int centerY = height / 2;
        radius = Math.min(width / 2, height / 2);
        circlePaint = new Paint();
        @SuppressLint("DrawAllocation")
        RadialGradient radialGradient = new RadialGradient(centerX, centerY, radius, Color.parseColor("#cc5316B6"),
                Color.parseColor("#5316B6"), Shader.TileMode.CLAMP);
        circlePaint.setShader(radialGradient);
        circlePaint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.INNER));
        canvas.drawCircle(centerX, centerY, radius, circlePaint);

        linePaint = new Paint();
        linePaint.setStrokeWidth(4);
        linePaint.setAntiAlias(true);
        linePaint.setStyle(Paint.Style.STROKE);
        linePaint.setStrokeJoin(Paint.Join.ROUND);
        CornerPathEffect cornerPathEffect = new CornerPathEffect(20);
        linePaint.setPathEffect(cornerPathEffect);//此处的200就是平滑的度数;
//        linePaint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.INNER));


        drawPaths(canvas, linePaint, currentBaseRadio, radius, width, height);
    }

    private void createAnimation() {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0.4f, 0.4f);
        valueAnimator.setDuration(3000);
        valueAnimator.setRepeatCount(ValueAnimator.INFINITE);
//        valueAnimator.setInterpolator(new OvershootInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            int count = 0;

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                count++;
                if (count % 4 == 1) {
                    float curValue = (float) animation.getAnimatedValue();

                    currentBaseRadio = (int) (radius * curValue + volume * 0.4 * radius / 100);
                    Log.i("tag", "----curValue:" + curValue + ',' + currentBaseRadio);
                    postInvalidate();
                }
            }
        });

        valueAnimator.start();
    }

    private void drawPaths(Canvas canvas, Paint paint, int currentBaseRadio, int radius, int width, int height) {
        //制作六个圆圈，圆圈半径相同，但是旋转角度不一样，互相错60度

        Random random = new Random();
        random.setSeed(System.currentTimeMillis());

//        int currentBaseRadio = (int) (radius * 0.8);
        //diff决定了几个折线之间的间距
        int diff = (int) ((radius - currentBaseRadio) * 0.4);
        int currentRadio = /*(int) (random.nextDouble() * diff) +*/ currentBaseRadio;
        int rotate = random.nextInt(30);

        createAndDrawPaths(canvas, paint, 6, Color.argb(150, 255, 255, 255), currentRadio, width, height, 0 + rotate);

        createAndDrawPaths(canvas, paint, 8, Color.argb(200, 255, 255, 255), (int) (currentRadio - diff * 0.2), width, height, 60 + rotate);

        createAndDrawPaths(canvas, paint, 7, Color.argb(150, 255, 255, 255), (int) (currentRadio - diff * 0.3), width, height, 120 + rotate);

        createAndDrawPaths(canvas, paint, 6, Color.argb(105, 255, 255, 255), (int) (currentRadio - diff * 0.4), width, height, 180 + rotate);

        createAndDrawPaths(canvas, paint, 7, Color.argb(55, 255, 255, 255), (int) (currentRadio - diff * 0.5), width, height, 240 + rotate);

        createAndDrawPaths(canvas, paint, 5, Color.argb(200, 255, 255, 255), (int) (currentRadio - diff * 0.6), width, height, 340 + rotate);
    }

    private void createAndDrawPaths(Canvas canvas, Paint paint, int pathCount, int color, int radius, int width, int height, int rotate) {
        canvas.save();
        if (rotate > 0)
            canvas.rotate(rotate, width / 2, height / 2);
        paint.setColor(color);
        Path path = createPath(pathCount, (int) (radius * 0.8f), width, height, 0.1, 0.1);
        canvas.drawPath(path, paint);
        canvas.restore();
    }

    private Path createPath(int n, int radius, int width, int height, double fra1, double fra2) {
        n = n * 2;
        if (n < 4) {
            return new Path();
        }
        List<Point> points = new ArrayList<>();
        Random random = new Random();
        random.setSeed(System.currentTimeMillis());
        for (int i = 0; i < n; i++) {
            int rad = i * 360 / n;
//            screenX = cartX + screen_width/2
//            screenY = screen_height/2 - cartY
            // 笛卡尔坐标系转换成屏幕坐标系
            double radiuss = radius;
//            radiuss = radiuss > 0.9 ? radius : 1;
//            radiuss = radiuss * radius;
            double randomV = random.nextDouble();
//            randomV = 1;
            int d = (int) (radius * fra1);
            if (i % 2 == 0) {
//            Log.e("TAG", "createPath: " + randomV + "," + i + ',' + (randomV > 0.5 ? d : -d));
                d = (int) (radius * fra2);
                radiuss = radius - d * randomV;
            } else {
                radiuss = radius + d;
            }
            Point point = new Point(width / 2 + (int) (radiuss * Math.cos(Math.toRadians(rad))),
                    height / 2 - (int) (radiuss * Math.sin(Math.toRadians(rad))));
            points.add(point);
        }
        Path path = new Path();
        path.moveTo(points.get(0).x, points.get(0).y);
        for (int i = 0; i < n; i++) {
            Point point2 = points.get(i);
            path.lineTo(point2.x, point2.y);
        }
        path.close();
        return path;
    }

    public void setVolume(int volume) {
        this.volume = volume;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.e(TAG, "onTouchEvent:" + event.getAction());
        if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
            setVolume(50);
        } else {
            setVolume(0);
        }
        return true;
    }
}
